import "@/libs/proto";
import "@/libs/wps/wps_sdk";
import { newDoc, openDoc, startCheckWps } from "@/libs/wps/wps";
import { newEtDoc, openEtDoc } from "@/libs/wps/et";
import "@/assets/iconfont";
import { Message, Notification } from "element-ui";
import moment from "moment";
// 引入音频文件
import audio from "@/assets/video/sound.mp3";
import store from "../store/store.js";

export default {
  install(Vue, options) {
    // 添加bus通讯
    Vue.prototype.$EventBus = new Vue();
    // 添加断线重连广播
    window.addEventListener("online", function() {
      Vue.prototype.$EventBus.$emit("online");
      Vue.prototype.$EventBus.$emit("socket_online");
    });
    window.addEventListener("offline", function() {
      Vue.prototype.$EventBus.$emit("offline");
    });
    // 添加浏览器关闭广播
    window.onbeforeunload = function(e) {
      store.commit("CLOSE_SOCKET_ALL");
      Vue.prototype.$EventBus.$emit("onbeforeunload");
      return;
    };
    // 当前时间格式化
    Vue.prototype.currentDay = function(type = 'time') {
      if (type === 'day') {
        return moment().format('YYYY-MM-DD')
      } else if (type === 'time') {
        return moment().format('YYYY-MM-DD HH:mm:ss')
      }
    };
    Vue.prototype.isNumber = function(val) {
      var regPos = /^\d+(\.\d+)?$/; //非负浮点数
      var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
      return regPos.test(val) || regNeg.test(val)
    };
    // 判断是否空对象
    Vue.prototype.isEmptyObj = function(obj) {
      if (Object.getOwnPropertySymbols(obj).length) {
        return false;
      }
      if (Object.getOwnPropertyNames(obj).length) {
        return false;
      }
      return true;
    };
    // 判断是否数组对象
    Vue.prototype.isArray = function(obj) {
      return obj instanceof Array;
    };

    // 判断是否Date对象
    Vue.prototype.isDate = function(obj) {
      return obj instanceof Date;
    };

    // 判断变量是否定义
    Vue.prototype.isSet = function(obj) {
      return typeof obj !== "undefined";
    };

    // 提示信息
    Vue.prototype.error = function(message) {
      Message({
        message: message,
        type: "error",
        duration: 3000,
        customClass:'message-weights'
      });
    };
    // 日期比较大小 a》b 返回true, 反false
    Vue.prototype.compareDate = function(dateTime1, dateTime2) {
      var formatDate1 = new Date(dateTime1);
      var formatDate2 = new Date(dateTime2);
      if (formatDate1 > formatDate2) {
        return true;
      } else {
        return false;
      }
    };
    // 提示信息
    Vue.prototype.warning = function(message) {
      Message({
        message: message,
        type: "warning",
        duration: 3000,
        customClass:'message-weights'
      });
    };
    // 右上角提示信息
    Vue.prototype.warningNotify = function(title, message) {
      Notification({
        message: message,
        title: title,
        type: "warning",
        duration: 3000,
        customClass:'message-weights'
      });
    };
    // 提示信息
    Vue.prototype.success = function(message) {
      Message({
        message: message,
        type: "success",
        duration: 3000,
        customClass:'message-weights'
      });
    };
    // 提示信息,倒计时
    Vue.prototype.successTime = function(message, time) {
      var a = Message({
        message: message,
        type: "success",
        duration: time * 1000
      });
      coutTime(time, message, a);
    };

    // 倒计时函数
    function coutTime(index, message, a) {
      setTimeout(function() {
        if (index == 0) {
          //5s结束后的操作
        } else {
          a.message = message + "，" + index + "s后将自动关闭";
          coutTime(--index, message, a);
        }
      }, 1000);
    }

    // 提示信息
    Vue.prototype.info = function(message) {
      Message({
        message: message,
        type: "info",
        duration: 3000
      });
    };
    // 打开新页面
    Vue.prototype.openPage = function(url, key) {
      let strWindowFeatures =
        "width=" +
        (window.screen.availWidth - 10) +
        ",height=" +
        (window.screen.availHeight - 60) +
        ",left=0,top=0,menubar=no,location=no,resizable=yes,scrollbars=true,status=true";
      var winObj = window.open(url, "B_page", strWindowFeatures);
      winObj.resizeTo(screen.availWidth, screen.availHeight);
      winObj.moveTo(0, 0);
      window.localStorage.setItem(key, "");
      var loop = setInterval(function() {
        if (winObj.closed) {
          clearInterval(loop);
          window.localStorage.setItem(key, "refresh");
        }
      }, 1);
    };

    // 打开新Tab页面
    Vue.prototype.openTabPage = function(url) {
      window.open(url, "_blank");
    };

    // 图片全屏展示
    Vue.prototype.showImg = function(url) {
    };

    // 获取高度css
    Vue.prototype.getHeight = function(height) {
      return { height: window.innerHeight - height + "px" };
    };

    // 获取传递给查询接口的字段
    Vue.prototype.setSearchFormApiData = function(
      searchFormData,
      tablePageData
    ) {
      const data = this.filterSearchFormData(searchFormData);
      data.pageIndex = tablePageData.pageIndex;
      data.pageSize = tablePageData.pageSize;
      return data;
    };

    // 过滤对接接口的参数，不传空值
    Vue.prototype.filterSearchFormData = function(searchFormData) {
      const data = {};
      Object.keys(searchFormData).forEach(key => {
        if (
          searchFormData[key] !== "" &&
          JSON.stringify(searchFormData[key]) !== "[]"
        ) {
          data[key] = searchFormData[key];
        }
      });
      return data;
    };

    // 参数装数组
    Vue.prototype.transferSearchFormData = function(searchFormData) {
      const data = [];
      Object.keys(searchFormData).forEach(key => {
        if (
          searchFormData[key] !== "" &&
          JSON.stringify(searchFormData[key]) !== "[]"
        ) {
          let tem = key.split("-");
          if (tem && tem.length > 0) {
            data.push({ id: tem[1], name: tem[0], value: searchFormData[key] });
          } else {
            data.push({ name: tem[0], value: searchFormData[key] });
          }
        }
      });
      return data;
    };

    // 获取传递给信息编辑接口的字段，过滤掉没有变化的字段 默认带上idKey字段 没有变化则返回 false
    Vue.prototype.getUpdateFormData = function(formData, idKey) {
      if (!this._formData) return formData;
      if (this._formData === JSON.stringify(formData)) {
        this.warning("未修改任何内容，不需要提交");
        return false;
      }
      idKey = idKey || "id";
      if (!formData[idKey]) {
        this.warning("无效的id-key");
        return false;
      }
      const data = {};
      const oldData = JSON.parse(this._formData);
      Object.keys(formData).forEach(key => {
        if (
          typeof formData[key] === "undefined" ||
          JSON.stringify(formData[key]) !== JSON.stringify(oldData[key])
        ) {
          data[key] = formData[key];
        }
      });
      data[idKey] = formData[idKey];
      return data;
    };

    // 检查api返回状态，异常则报错
    Vue.prototype.checkApiSuccess = function(res) {
      if (res.errorCode === "0") {
        return true;
      } else {
        this.error(res.errorMsg);
      }
      return false;
    };

    // 表单组件字段重置方法
    Vue.prototype.resetForm = function(ref) {
      this.$refs[ref].$emit("resetForm");
    };

    //  获取下载文件流的文件名称
    Vue.prototype.getFileName = function(disposition) {
      var fileName = "";
      if (disposition) {
        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        var matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
          fileName = matches[1].replace(/['"]/g, "");
        }
      }
      return decodeURIComponent(fileName);
    };

    // 播放提示音
    Vue.prototype.playVideo = function(url) {
      var music = new Audio();
      music.src = audio; //这里替换成一个有效的音频文件地址以方便测试
      music.loop = false;
      music.play();
    };

    // 表单组件刷新表单方法 重置表单默认值
    Vue.prototype.refreshForm = function(ref) {
      this.$refs[ref].$emit("refreshForm");
    };
    // 图片地址
    Vue.prototype.fullImagePath = function(uri) {
      if (uri) {
        if (
          uri.indexOf("http") === 0 ||
          uri.indexOf("../") === 0 ||
          uri.indexOf("data:") === 0
        ) {
          return uri;
        } else {
          return window.api.imageDomain + uri;
        }
      } else {
        return "";
      }
    };
    // 表单组件字段校验方法
    Vue.prototype.validateForm = function(ref, func) {
      return this.$refs[ref].$refs["form"].validate(func).catch(err => {
        return err;
      });
    };

    // 设置表单数据方法
    Vue.prototype.setFormData = function(data, ref) {
      this.formData = JSON.parse(JSON.stringify(data));
      this._formData = JSON.stringify(data);

      if (ref) {
        setTimeout(() => {
          this.refreshForm(ref);
        }, 0);
      }
    };

    // 给表单提交使用的操作确认方法
    Vue.prototype.confirmForm = function(param) {
      if (typeof param === "string") {
        param = { title: param };
      }
      let { title, subTitle, confirmText, cancelText, type } = param;

      title = title || "提示信息";
      subTitle = subTitle || "提示";
      confirmText = confirmText || "确定";
      cancelText = cancelText || "取消";
      type = type || "warning";

      return this.$confirm(title, subTitle, {
        confirmButtonText: confirmText,
        cancelButtonText: cancelText,
        type: type
      })
        .then()
        .catch(err => {
          return err;
        });
    };
    // 根据值集CODE获取值集选项列表
    Vue.prototype.getDictionary = function(code, type = 'default') {
      if (!code) return;
      let DictionaryData = window.sessionStorage.getItem("allDic");
      let arr = JSON.parse(DictionaryData);
      let obj = arr.find(v => v.keyword === code);
      switch (type) {
        case "default":
          if (obj) return obj.children;
          return [];
        case "map":
          let temp = {}
          if (obj) {
            for (let i = 0; i < obj.children.length; i++) {
              temp[obj.children[i].keyword] = obj.children[i].label
            }
          }
          return temp
      }
    };
    // 根据值集pCode获取子集值集选项列表
    Vue.prototype.getChildDictionary = function(code, childCode) {
      console.log(code, childCode);
      if (!childCode) return;
      if (!code) return;
      let DictionaryData = window.sessionStorage.getItem("allDic");
      let arr = JSON.parse(DictionaryData);
      let obj = arr.find(v => v.keyword === code);
      let tem = [];
      if (obj) {
        obj.children.map(item => {
          if (childCode) {
            if (item.keyword === childCode) {
              tem = item.children;
            }
          }
        });
      }
      return tem;
    };
    // // 根据值集pCode获取子集值集选项列表
    // Vue.prototype.getChildDictionary = function (code, child) {
    //   let result=[]
    //   if (child && code) {
    //     for (let i = 0; i < child.length; i++) {
    //       let item = child[i]
    //       console.log(item.value,item.children,99999999999)
    //       if (item) {
    //         if (code === item.value) {
    //           console.log(777777777777,item.children)
    //           result =item.children
    //         } else {
    //           if (item.children&&item.length>0) {
    //             console.log(item.children,5555)
    //             result =this.getChildDictionary(code, item.children)
    //           }
    //         }
    //       }
    //     }
    //   }
    //   return result
    // }
    // 根据值集值Value转换成名称显示
    Vue.prototype.showDictionary = function(code, value) {
      let options = [];

      if (typeof code === "object") {
        code.forEach(c => {
          options = options.concat(this.getDictionary(c));
        });
      } else {
        options = this.getDictionary(code);
      }
      if (options && options.length) {
        let opt = options.find(v => v.keyword === value);
        if (opt) {
          return opt.label;
        }
        return "";
      }
      return "";
    };

    /**
     * 描述：生成GUID
     * 时间： 2020/12/11
     */
    Vue.prototype.GUID = function() {
      let tem = this.S4();
      console.log(tem);
      return (
        this.S4() +
        this.S4() +
        "-" +
        this.S4() +
        "-" +
        this.S4() +
        "-" +
        this.S4() +
        "-" +
        this.S4() +
        this.S4() +
        this.S4()
      );
    };

    Vue.prototype.S4 = function() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    /** wps 相关  开始**/

    // doc 相关
    Vue.prototype.openDocVue = function(
      userName,
      fieldName,
      documentId,
      flowId,
      taskId,
      instanceId,
      protectType,
      socketClientId
    ) {
      openDoc(
        userName,
        fieldName,
        documentId,
        flowId,
        taskId,
        instanceId,
        protectType,
        socketClientId
      );
    };

    Vue.prototype.newDocVue = function(
      userName,
      documentId,
      flowId,
      taskId,
      instanceId,
      socketClientId,
      newFileName
    ) {
      newDoc(
        userName,
        documentId,
        flowId,
        taskId,
        instanceId,
        socketClientId,
        newFileName
      );
    };

    // et 相关
    Vue.prototype.newEtVue = function(
      userName,
      documentId,
      socketClientId,
      newFileName
    ) {
      newEtDoc(userName, documentId, socketClientId, newFileName);
    };
    Vue.prototype.openEtVue = function(
      userName,
      fieldName,
      documentId,
      protectType,
      socketClientId
    ) {
      openEtDoc(userName, fieldName, documentId, protectType, socketClientId);
    };

    /** wps 相关  结束 **/
  }
};
